<?php

/**
 * 
 * 1、车主不卖进入磋商失败的车辆，
 *    超过检测时间72小时则将该车辆插入au_car_sale表中成为车源销售
 * 
 * 
 * 
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER ['REQUEST_URI'])) {
    die('error');
}
if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}


require_once (API_ROOT_PATH . '/../inc/Config.php');
require_once (API_ROOT_PATH . '/../inc/dblink.php');
require_once (API_ROOT_PATH . '/../inc/Mysql.php');

function getNextSleepSecond() {
    $date1 = time();
    $date2 = date('Y-m-d H:i:s', strtotime('+1 hour', $date1));

    $date2 = strtotime($date2);
    $s = $date2 - $date1;

    $date1 = date('Y-m-d H:i:s', $date1);
    $date2 = date('Y-m-d H:i:s', $date2);

    print_r("currtime:$date1   nexttime:$date2   timediff:$s\n");

    return $s;
}

while (true) {
    $paimai_db = new Mysql(MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE);
    /**
     * 查询所有磋商失败且没有在车源销售中的车辆
     */
    $sql = "SELECT c.car_id,c.posttime FROM au_order o 
                INNER JOIN au_cars AS c ON c.car_id=o.car_id 
                INNER JOIN au_car_owner AS co ON co.owner_id=c.owner_id 
                WHERE ( o.status = '12' AND o.fail_type = 6 AND o.unsold_service_id > 0 ) 
                AND c.car_id NOT IN(SELECT car_id FROM au_car_sale)
                ORDER BY o.order_id DESC";
    $result = $paimai_db->query($sql);
    while ($row = $paimai_db->fetch($result)) {
        $rows[] = $row;
    }
    foreach ($rows as $k => $v) {
        if (time() - strtotime($v['posttime']) > 60 * 60 * 24 * 3) {
            $ok = $paimai_db->query("INSERT INTO au_car_sale ('car_id',car_status) VALUES ({$v['car_id']},1)");
            echo '拍单已过72小时，已推送到车源销售'.date('Y-m-d H:i:s',time())."\n";    
        }
    }
    if (!$row && !$row1) {
        $sleeptimes = getNextSleepSecond();
        print_r("sleep:" . $sleeptimes . "\n");
        sleep($sleeptimes);
        continue;
    }

    $paimai_db->close();

    unset($paimai_db);
    $paimai_db = null;
}
